package com.xwltz.core.utils.web;

import javax.net.ssl.*;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Arrays;

/**
 * @description SSLSocketClient
 * @information on version 1.0 be created by @xwltz at 2021/11/23 11:41
 */

public class SSLSocketClient {
	public static SSLSocketFactory getSSLSocketFactory() {
		try {
			SSLContext sslContext = SSLContext.getInstance("SSL");
			sslContext.init(null, getTrustManager(), new SecureRandom());
			return sslContext.getSocketFactory();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private static TrustManager[] getTrustManager() {
		return new TrustManager[]{
				new X509TrustManager() {
					@Override
					public void checkClientTrusted(X509Certificate[] chain, String authType) {
						//不校检客户端证书
					}

					@Override
					public void checkServerTrusted(X509Certificate[] chain, String authType) {
						//不校检服务器证书
					}

					@Override
					public X509Certificate[] getAcceptedIssuers() {
						return new X509Certificate[]{};
						//Okhttp 3.0 以前返回null,3.0以后返回new X509Certificate[]{};
					}
				}
		};
	}

	public static HostnameVerifier getHostnameVerifier() {
		return (s, sslSession) -> {
			//未真正校检服务器端证书域名
			return true;
		};
	}

	public static X509TrustManager getX509TrustManager() {
		X509TrustManager trustManager = null;
		try {
			TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
			trustManagerFactory.init((KeyStore) null);
			TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
			if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
				throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
			}
			trustManager = (X509TrustManager) trustManagers[0];
		} catch (Exception e) {
			e.printStackTrace();
		}

		return trustManager;
	}
}
